package com.hub.realtime.tool;

import cn.hutool.json.JSONUtil;
import com.hub.realtime.common.core.domain.AjaxResult;
import com.hub.realtime.model.EsConfigRequest;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@RestController
@RequestMapping("/tool/es")
public class EsConfigController {

    @PostMapping
    public AjaxResult postEsApi(@RequestBody EsConfigRequest esConfigRequest) {
        String[] split = esConfigRequest.getApplication().split(";");

        BASE64Encoder base64Encoder = new BASE64Encoder();
        for (String app : split) {
            String template = getTemplate(esConfigRequest.getTemplateContent(), app, esConfigRequest.getEnv().toLowerCase(), esConfigRequest.getTemplate());
            String encode = base64Encoder.encode(template.getBytes(StandardCharsets.UTF_8));
            String apiUrl = esConfigRequest.getApiUrl().concat("/").concat(app + "/filebeat?skip=hakutaku");
            Map<String, String> param = new HashMap<>();
            param.put("containerInput", encode.replace("\n", ""));
            postEnvAppConfig(apiUrl, esConfigRequest.getEnv(), JSONUtil.toJsonStr(param));
        }
        return AjaxResult.success("请求成功");
    }


    private String getTemplate(String tmp, String app, String env, String template) {
        if (env.equalsIgnoreCase("CSPRD")) {
            return String.format(tmp, app);
        } else {
            if (template.equals("t2")) {
                return String.format(tmp, app, env, app, env);
            } else {
                return String.format(tmp, app, env);
            }
        }

    }


    public static void postEnvAppConfig(String url, String env, String requestBody) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut put = new HttpPut(url);
        put.addHeader("Content-Type", "application/json");
        put.addHeader("env", env.toUpperCase());

        HttpEntity entity = new StringEntity(requestBody, "Utf-8");
        put.setEntity(entity);


        CloseableHttpResponse response;
        HttpEntity httpEntity;
        try {
            response = httpClient.execute(put);
            // 获得响应的实体对象
            httpEntity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            String entityStr = EntityUtils.toString(httpEntity, "UTF-8");
            System.out.println("PUT请求结果：" + entityStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
